package com.work.leecode.string.middle;

/**
 * 最长回文子串
 */
public class Lc5 {
    //动态规划
    public String longestPalindrome(String s) {
        //前置校验
        if (s == null || s.length() < 2) {
            return s;
        }
        int len = s.length();
        //dp[i][j]表示子串s[i..j]是否是回文串
        boolean[][] dp = new boolean[len][len];

        //初始化，单个字符肯定是回文串
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }


        //辅助变量
        int start = 0;
        int maxLen = 1;

        //从长度为2的子串开始判断
        for (int L = 2; L <= len; L++) {
            for (int i = 0; i < len; i++) {
                //右边界索引
                int j = L + i - 1; //j-i+1 = L

                //边界判断，j最大为len-1
                if (j >= len) {
                    break;
                }

                //左右边界不相等
                if (s.charAt(i) != s.charAt(j)) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {//长度为2和长度为3的子串都是回文串，因为长度为3时，左右相等即可，与中间单个字符无关
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }

                if (dp[i][j] && j - i + 1 > maxLen) {
                    start = i;
                    maxLen = j - i + 1;
                }
            }
        }
        return s.substring(start, start + maxLen);
    }

    //暴力解法
    public String longestPalindrome2(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }

        int start = 0;
        int maxLen = 1;
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (isPalindrome(arr, i, j) && j - i + 1 > maxLen) {
                    start = i;
                    maxLen = j - i + 1;
                }
            }
        }
        return s.substring(start, start + maxLen);
    }

    //判断是否是回文串
    public boolean isPalindrome(char[] chars, int i, int j) {
        while (i <= j) {
            if (chars[i] != chars[j]) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}
